<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert title="注意：只允许为第三级分类设置参数！" type="warning" show-icon :closable="false"></el-alert>

      <div class="block">
        <el-cascader expand-trigger="hover" :options="goodsCateList" placeholder="选择商品分类"
         v-model="selectKeys"  @change="selectGoodsChange" :props="goodsCateProps" style="margin-top: 15px">
        </el-cascader>
      </div>
      
      <el-tabs v-model="activeName" @tab-click="paramsTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-row>
            <el-col>
              <el-button type="primary" @click="addDialogVisible = true" :disabled="addBtn">添加参数</el-button>
            </el-col>
          </el-row>
          <el-table :data="manyData" border stripe style="width: 100%; margin-top: 15px">
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="">
                    <el-tag :key="tag" v-for="tag in props.row.attr_vals.split(',')" closable :disable-transitions="false" @close="handleClose(props.row, tag)">
                      {{ tag }}
                    </el-tag>
                    <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" 
                    size="small" @keyup.enter.native="handleInputConfirm(props.row)" @blur="handleInputConfirm(props.row)"
                    >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="manyEdit(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="manyDel(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-row>
            <el-col>
              <el-button type="primary" @click="addOnlyDialogVisible = true" :disabled="addBtn">添加属性</el-button>
            </el-col>
          </el-row>
          <el-table :data="onlyData" border stripe style="width: 100%; margin-top: 15px">
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="">
                    <el-tag :key="tag" v-for="tag in props.row.attr_vals.split(',')" closable :disable-transitions="false" @close="handleClose1(props.row, tag)">
                      {{ tag }}
                    </el-tag>
                    <el-input class="input-new-tag" v-if="inputVisible1" v-model="inputValue1" ref="saveTagInput1" 
                    size="small" @keyup.enter.native="handleInputConfirm1(props.row)" @blur="handleInputConfirm1(props.row)"
                    >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput1">+ New Tag</el-button>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="onlyEdit(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="onlyDel(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

      </el-tabs>
    </el-card>
    
    <!-- 添加动态参数对话框 -->
    <el-dialog title="添加动态参数" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <el-form :model="addDialogForm" :rules="addFormRules" ref="addDialogFormRef" label-width="100px" class="demo-addDialogForm">
        <el-form-item label="动态参数" prop="attr_name">
          <el-input v-model="addDialogForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- footer -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogClosed">取 消</el-button>
        <el-button type="primary" @click="addAttr">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加静态属性对话框 -->
    <el-dialog title="添加静态属性" :visible.sync="addOnlyDialogVisible" width="50%" @close="addOnlyDialogClosed">
      <el-form :model="addOnlyDialogForm" :rules="addOnlyFormRules" ref="addOnlyDialogFormRef" label-width="100px" class="demo-addOnlyDialogForm">
        <el-form-item label="静态属性" prop="attr_name">
          <el-input v-model="addOnlyDialogForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- footer -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addOnlyDialogClosed">取 消</el-button>
        <el-button type="primary" @click="addOnlyAttr">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 动态、 编辑 -->
    <el-dialog title="编辑动态参数" :visible.sync="editManyDialogVisible" width="50%" @close="editManyDialogClosed">
      <el-form :model="editManyDialogForm" :rules="editManyFormRules" ref="editManyDialogFormRef" label-width="100px" class="demo-editManyDialogForm">
        <el-form-item label="动态参数" prop="attr_name">
          <el-input v-model="editManyDialogForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- footer -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editManyDialogClosed">取 消</el-button>
        <el-button type="primary" @click="editManyAttr">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 动态、 删除 -->

    <!-- 静态、 编辑 -->
    <el-dialog title="编辑静态属性" :visible.sync="editOnlyDialogVisible" width="50%" @close="editOnlyDialogClosed">
      <el-form :model="editOnlyDialogForm" :rules="editOnlyFormRules" ref="editOnlyDialogFormRef" label-width="100px" class="demo-editOnlyDialogForm">
        <el-form-item label="静态属性" prop="attr_name">
          <el-input v-model="editOnlyDialogForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- footer -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editOnlyDialogClosed">取 消</el-button>
        <el-button type="primary" @click="editOnlyAttr">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 静态、 删除 -->
  </div>
</template>
<script>
export default {
  data() {
    return {
      selectKeys: [],
      manyData: [],
      onlyData: [],
      goodsCateList: [],
      addBtn: true,
      addOnlyDialogVisible: false,
      addDialogForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入动态参数名', trigger: 'blur' },
          { min: 1, max: 15, message: '动态参数长度在 1 到 15 个字符', trigger: 'blur' }
        ],
      },
      addOnlyDialogForm: {
        attr_name: ''
      },
      addOnlyFormRules: {
        attr_name: [
          { required: true, message: '请输入静态属性名', trigger: 'blur' },
          { min: 1, max: 15, message: '动态参数长度在 1 到 15 个字符', trigger: 'blur' }
        ],
      },
      addDialogVisible: false,

      thisAttrId: '',
      editManyDialogVisible: false,
      editManyDialogForm: {
        attr_name: ''
      },
      editManyFormRules: {
        attr_name: [
          { required: true, message: '请输入动态参数名', trigger: 'blur' },
          { min: 1, max: 15, message: '动态参数长度在 1 到 15 个字符', trigger: 'blur' }
        ],
      },

      editOnlyDialogVisible: false,
      editOnlyDialogForm: {
        attr_name: ''
      },
      editOnlyFormRules: {
        attr_name: [
          { required: true, message: '请输入动态参数名', trigger: 'blur' },
          { min: 1, max: 15, message: '动态参数长度在 1 到 15 个字符', trigger: 'blur' }
        ],
      },

      goodsCateProps: {
        value: 'cat_id',
        label: 'cat_name',
        childer: 'children',
      },
      activeName: 'many',

      inputVisible: false,
      inputValue: '',

      inputVisible1: false,
      inputValue1: '',
    }
  },
  created() {
    this.getGoodsCate()
  },
  methods: {
    getGoodsCate() {
      this.$http.get('categories').then(res => {
        this.goodsCateList = res.data.data
      })
    },
    getGoodAttributes() {
      // many
      this.$http.get(`categories/${this.selectKeys[2]}/attributes`, {
        params: {
          sel: 'many'
        }
      }).then(res => {
        console.log(res.data)
        this.manyData = res.data.data
      })

      // only
      this.$http.get(`categories/${this.selectKeys[2]}/attributes`, {
        params: {
          sel: 'only'
        }
      }).then(res => {
        console.log(res.data)
        this.onlyData = res.data.data
      })
    },
    selectGoodsChange() {
      if(this.selectKeys.length !== 3){
        // 说明选择的不是三级
        this.$message.error("请选择三级分类")
        this.selectKeys = []
      }else {
        // 是三级分类
        this.getGoodAttributes()
        // 开启按钮
        this.addBtn = false
        console.log(this.selectKeys)
      }
    },
    paramsTabClick() {
      console.log("切换")
    },
    addDialogClosed() {
      this.$refs.addDialogFormRef.resetFields();
      this.addDialogVisible = false
    },
    addAttr() {
      this.$refs.addDialogFormRef.validate((valid) => {
        if (valid) {
          this.$http.post(`categories/${this.selectKeys[2]}/attributes`, {
            attr_name: this.addDialogForm.attr_name,
            attr_sel: 'many',
            attr_vals: ''
          }).then(res => {
            if(res.data.meta.status !== 201) {
              this.$message.error('创建失败(请检查是否选中商品) :' + res.data.meta.msg)
            }else {
              this.getGoodAttributes()
              this.addDialogVisible = false
              this.$message.success("创建成功")
            }
          })
        } else {
          this.$message.error("请重新输入")
          return false;
        }
      });
      
    },
    addOnlyDialogClosed() {
      this.$refs.addOnlyDialogFormRef.resetFields();
      this.addOnlyDialogVisible = false
    },
    addOnlyAttr() {
      this.$refs.addOnlyDialogFormRef.validate((valid) => {
        if (valid) {
          this.$http.post(`categories/${this.selectKeys[2]}/attributes`, {
            attr_name: this.addOnlyDialogForm.attr_name,
            attr_sel: 'only',
            attr_vals: ''
          }).then(res => {
            if(res.data.meta.status !== 201) {
              this.$message.error('创建失败: (请检查是否选中商品)' + res.data.meta.msg)
            }else {
              this.getGoodAttributes()
              this.addOnlyDialogVisible = false
              this.$message.success("创建成功")
            }
          })
        } else {
          this.$message.error("请重新输入")
          return false;
        }
      });
      
    },
    editManyDialogClosed() {
      this.$refs.editManyDialogFormRef.resetFields()
      this.editManyDialogVisible = false
    },
    editManyAttr() {
      this.$refs.editManyDialogFormRef.validate((valid) => {
        if (valid) {
          this.$http.put(`categories/${this.selectKeys[2]}/attributes/${this.thisAttrId}`, {
            attr_name: this.editManyDialogForm.attr_name,
            attr_sel: 'many',
            attr_vals: ''
          }).then(res => {
            if(res.data.meta.status !== 200) {
              this.$message.error('更新失败 :' + res.data.meta.msg)
            }else {
              this.getGoodAttributes()
              this.editManyDialogVisible = false
              this.$message.success("更新成功")
            }
          })
        } else {
          this.$message.error("请重新输入")
          return false;
        }
      });
    },
    manyEdit(scopeRow) {
      this.editManyDialogVisible = true
      this.editManyDialogForm.attr_name = scopeRow.attr_name
      this.thisAttrId = scopeRow.attr_id
    },
    
    editOnlyDialogClosed() {
      this.$refs.editOnlyDialogFormRef.resetFields()
      this.editOnlyDialogVisible = false
    },
    editOnlyAttr() {
      this.$refs.editOnlyDialogFormRef.validate((valid) => {
        if (valid) {
          this.$http.put(`categories/${this.selectKeys[2]}/attributes/${this.thisAttrId}`, {
            attr_name: this.editOnlyDialogForm.attr_name,
            attr_sel: 'only',
            attr_vals: ''
          }).then(res => {
            if(res.data.meta.status !== 200) {
              this.$message.error('更新失败 :' + res.data.meta.msg)
            }else {
              this.getGoodAttributes()
              this.editOnlyDialogVisible = false
              this.$message.success("更新成功")
            }
          })
        } else {
          this.$message.error("请重新输入")
          return false;
        }
      });
    },
    onlyEdit(scopeRow) {
      this.editOnlyDialogVisible = true
      this.editOnlyDialogForm.attr_name = scopeRow.attr_name
      this.thisAttrId = scopeRow.attr_id
    },
    manyDel(scopeRow) {
      this.$confirm("此操作将永久删除该用户,是否继续?", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$http.delete(`categories/${this.selectKeys[2]}/attributes/${scopeRow.attr_id}`).then(res => {
          // console.log(res.data)
          if(res.data.meta.status !== 200){
            this.$message.error("删除失败:" + res.data.meta.msg)
          }else {
            this.$message.success("删除成功")
            this.getGoodAttributes()
          }
        })
      }).catch(() => {
        this.$message.info("已取消删除")
      });
    },
    onlyDel(scopeRow) {
      this.$confirm("此操作将永久删除该用户,是否继续?", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$http.delete(`categories/${this.selectKeys[2]}/attributes/${scopeRow.attr_id}`).then(res => {
          // console.log(res.data)
          if(res.data.meta.status !== 200){
            this.$message.error("删除失败:" + res.data.meta.msg)
          }else {
            this.$message.success("删除成功")
            this.getGoodAttributes()
          }
        })
      }).catch(() => {
        this.$message.info("已取消删除")
      });
    },
    fliterArr(arr) {
      for(var i = 0 ;i<arr.length;i++) {  
        if(arr[i] == "" || arr[i] == null || typeof(arr[i]) == "undefined")  {  
          arr.splice(i,1);  
          i= i-1;  
        }  
      }
    },

    // 标签
    handleClose(propsRow, tag) {
      let arr = propsRow.attr_vals.split(',')
      arr.splice(arr.indexOf(tag), 1)
      this.fliterArr(arr)
      let newAttrVals = arr.join(',')
      this.$http.put(`categories/${propsRow.cat_id}/attributes/${propsRow.attr_id}`, {
        attr_name: propsRow.attr_name,
        attr_sel: 'many',
        attr_vals: newAttrVals
      }).then(res => {
        console.log(res.data)
        if(res.data.meta.status !== 200) {
          this.$message.error('删除标签失败 :' + res.data.meta.msg)
        }else {
          this.getGoodAttributes()
          this.$message.success("删除标签成功")
        }
      })
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm(propsRow) {
      let inputValue = this.inputValue;
      let arr = propsRow.attr_vals.split(',')
      this.fliterArr(arr)
      var flag = true
      for (var i = 0; i < arr.length; i++) {
        if(arr[i] === inputValue){
          this.$message.error("不要重复添加")
          flag = false
        }
      }
      if(inputValue === "") {
        this.$message.error("不要添加空值")
        flag = false
      }
      if(flag) {
        arr.push(inputValue)
        let newAttrVals = arr.join(',')
        console.log(propsRow)
        if (inputValue) {
          // 添加动态参数
          this.$http.put(`categories/${propsRow.cat_id}/attributes/${propsRow.attr_id}`, {
            attr_name: propsRow.attr_name,
            attr_sel: 'many',
            attr_vals: newAttrVals
          }).then(res => {
            console.log(res.data)
            if(res.data.meta.status !== 200) {
              this.$message.error('添加标签失败 :' + res.data.meta.msg)
            }else {
              this.getGoodAttributes()
              this.$message.success("添加标签成功")
            }
          })
        }
      }
      this.inputVisible = false;
      this.inputValue = '';
    },

    // 标签2 
    handleClose1(propsRow, tag) {
      let arr = propsRow.attr_vals.split(',')
      arr.splice(arr.indexOf(tag), 1)
      this.fliterArr(arr)
      let newAttrVals = arr.join(',')
      this.$http.put(`categories/${propsRow.cat_id}/attributes/${propsRow.attr_id}`, {
        attr_name: propsRow.attr_name,
        attr_sel: 'only',
        attr_vals: newAttrVals
      }).then(res => {
        console.log(res.data)
        if(res.data.meta.status !== 200) {
          this.$message.error('删除标签失败 :' + res.data.meta.msg)
        }else {
          this.getGoodAttributes()
          this.$message.success("删除标签成功")
        }
      })
    },
    showInput1() {
      this.inputVisible1 = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput1.$refs.input.focus();
      });
    },
    handleInputConfirm1(propsRow) {
      let inputValue1 = this.inputValue1;
      let arr = propsRow.attr_vals.split(',')
      this.fliterArr(arr)
      var flag = true
      for (var i = 0; i < arr.length; i++) {
        if(arr[i] === inputValue1){
          this.$message.error("不要重复添加")
          flag = false
        }
      }
      if(inputValue1 === "") {
        this.$message.error("不要添加空值")
        flag = false
      }
      if(flag) {
        arr.push(inputValue1)
        let newAttrVals = arr.join(',')
        console.log(propsRow)
        if (inputValue1) {
          // 添加动态参数
          this.$http.put(`categories/${propsRow.cat_id}/attributes/${propsRow.attr_id}`, {
            attr_name: propsRow.attr_name,
            attr_sel: 'only',
            attr_vals: newAttrVals
          }).then(res => {
            console.log(res.data)
            if(res.data.meta.status !== 200) {
              this.$message.error('添加标签失败 :' + res.data.meta.msg)
            }else {
              this.getGoodAttributes()
              this.$message.success("添加标签成功")
            }
          })
        }
      }
      this.inputVisible1 = false;
      this.inputValue1 = '';
    }
  },
}
</script>
<style lang="scss" scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>